package com.free.bsf.sentinel;

import com.alibaba.csp.sentinel.config.SentinelConfig;
import com.free.bsf.core.config.CoreProperties;
import com.free.bsf.core.util.NetworkUtils;
import com.free.bsf.core.util.PropertyUtils;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.util.StringUtils;

import java.io.File;

/**
 * @author: chejiangyi
 * @version: 2019-06-14 09:41
 **/
public class SentinelApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
    @Override
    public void initialize(ConfigurableApplicationContext context) {
        this.initializeSystemProperty(context);
    }

    void initializeSystemProperty(ConfigurableApplicationContext context) {
        org.springframework.core.env.Environment environment = context.getEnvironment();
        if("false".equalsIgnoreCase(environment.getProperty(CoreProperties.BsfEnabled))){
            return;
        }
        String propertyValue = environment.getProperty(SentinelProperties.SpringApplicationName);
        if (StringUtils.isEmpty(propertyValue)) {
           return;
        }
        setProperty(SentinelProperties.ProjectName, PropertyUtils.getPropertyCache(SentinelProperties.SpringApplicationName,""));
        setProperty(SentinelProperties.CspSentinelLogDir, "logs"+ File.separator+"csp"+File.separator);
        setProperty(SentinelProperties.CspSentinelLogUsePid, "true");
        setProperty(SentinelProperties.CspSentinelDashboardServer, PropertyUtils.getPropertyCache(SentinelProperties.CspSentinelDashboardServer,""));
        //setProperty(SentinelProperties.CspSentinelHeartBeatClientIp, NetworkUtils.getIpAddress());
    }

    void setProperty(String key,String propertyValue)
    {
        PropertyUtils.setDefaultInitProperty(SentinelApplicationContextInitializer.class,SentinelProperties.Project,key,propertyValue,
                "初始化sentinel配置");
        //同步刷新sentinel缓存
        SentinelConfig.setConfig(key,propertyValue);
    }
}
